﻿using QRCoder;
using System.Drawing;

namespace BDRUtils.Utility
{
    /// <summary>
    /// 二维码编码器
    /// </summary>
    public class QRCoderHelper
    {
        /// <summary>
        /// 生成二维码
        /// </summary>
        /// <param name="msg">信息</param>
        /// <param name="version">版本 1 ~ 40</param>
        /// <param name="pixel">像素点大小</param>
        /// <param name="icon_path">图标路径</param>
        /// <param name="icon_size">图标尺寸</param>
        /// <param name="icon_border">图标边框厚度</param>
        /// <param name="white_edge">二维码白边</param>
        /// <returns>位图</returns>
        public static Bitmap GetBinaryCode(string msg, int version, int pixel, string iconPath, int iconSize, int iconBorder, bool whiteEdge)
        {
            using (QRCodeGenerator code_generator = new QRCodeGenerator())
            {
                QRCodeData codeData = code_generator.CreateQrCode(
                    msg,
                    QRCodeGenerator.ECCLevel.M/* 这里设置容错率的一个级别 */,
                    true,
                    true,
                    QRCodeGenerator.EciMode.Utf8,
                    version);

                using (QRCode code = new QRCode(codeData))
                {
                    using (Bitmap icon = new Bitmap(iconPath))
                    {
                        Bitmap bmp = code.GetGraphic(pixel, Color.Black, Color.White, icon, iconSize, iconBorder, whiteEdge);
                        return bmp;
                    }
                }
            }

        }

        /// <summary>
        /// 生成二维码
        /// </summary>
        /// <param name="url">存储内容</param>
        /// <param name="pixel">像素大小</param>
        /// <returns></returns>
        public Bitmap GetQRCode(string url, int pixel)
        {
            QRCodeGenerator generator = new QRCodeGenerator();
            QRCodeData codeData = generator.CreateQrCode(url, QRCodeGenerator.ECCLevel.M, true);
            QRCode qrcode = new QRCode(codeData);

            Bitmap qrImage = qrcode.GetGraphic(pixel, ColorTranslator.ToHtml(Color.Black), ColorTranslator.ToHtml(Color.White), true);

            return qrImage;
        }
    }
}
